//
//  MNDAutoTenderPlusViewController.m
//  minidai
//
//  Created by Vitas on 2018/7/12.
//  Copyright © 2018年 迷你贷. All rights reserved.
//

#import "MNDAutoTenderPlusViewController.h"
#import "MNDAutoTenderPlusCell.h"
#import "MNDPlusDetailRootViewController.h"
#import "SYRefreshControl.h"
#import "MNDPlusListModel.h"
#import "MNDWhatIsPlusTenderViewController.h"
#import "MNDCommonProblemModel.h"


#define kMNDAutoTenderPlusCell @"MNDAutoTenderPlusCell"

@interface MNDAutoTenderPlusViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) UIView *placeHolderMaskView;
@property (assign,nonatomic) NSInteger pageNumber;
@property(nonatomic, strong) NSMutableArray *dataArray;
@property(nonatomic, strong) NSMutableArray *problemArray;

@end

@implementation MNDAutoTenderPlusViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    kdeclare_weakself;
    [SYRefreshControl configGifMJRefresh:self.tableView refreshType:MJRefreshSupportALl beginRefresh:YES timeLabelHidden:YES stateLabelHidden:YES refreshBlock:^{
        
        [weakSelf loadData:YES];
        [weakSelf loadCommonProblemData];
    } loadMoreBlock:^{
        [weakSelf loadData:NO];
    }];
    
    [self setupUI];
    [self loadCommonProblemData];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self loadData:YES];
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)problemArray {
    if (!_problemArray) {
        _problemArray = [NSMutableArray array];
    }
    return _problemArray;
}


- (void)setupUI {
    [self creatMaskView];
    
}

- (void)loadData:(BOOL)isPullDown {
    kdeclare_weakself;
    //请求的参数
    NSDictionary *parametersDict;
    //如果下拉
    if (isPullDown) {
        _pageNumber = 1;
    
    }else {
        _pageNumber++;
    }
    parametersDict = @{@"perpage":@(_pageNumber),
                       @"pagesize": @"10",
                       @"plan_status":@"1"
                       };
    NSDictionary *params = [MNDSign signedParamWithDict:parametersDict];
    [APIManager sendRequestWithURL:API_AUTO_PLUS_LIST parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            if(isPullDown) {
                [weakSelf.dataArray removeAllObjects];
            }
            MNDPlusListModel *listModel = [MNDPlusListModel mj_objectWithKeyValues:responseModel.data];
            NSArray *array = listModel.tender_plan;
            [weakSelf.dataArray addObjectsFromArray:array];
            if (weakSelf.dataArray.count <= 0) {
                weakSelf.placeHolderMaskView.hidden = NO;
            }else {
                weakSelf.placeHolderMaskView.hidden = YES;
            }
            [SYRefreshControl configAfterLoading:self.tableView hasData:array.count];
            [weakSelf.tableView reloadData];
        }else {
            [SYRefreshControl configAfterLoading:self.tableView hasData:NO];
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
        
        
    } onFailure:^(NSError *error) {
        [SYRefreshControl configAfterLoading:self.tableView hasData:NO];
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)loadCommonProblemData {
    kdeclare_weakself;
    [APIManager sendRequestWithURL:API_AUTO_PLUS_PROBLEM parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakSelf.problemArray = [MNDCommonProblemModel mj_objectArrayWithKeyValuesArray:responseModel.data[@"tender"]];
            [weakSelf.tableView reloadData];
        }else {
            
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (IBAction)clickBottomButton:(UIButton *)sender {
    __weak MNDWhatIsPlusTenderViewController *alertVC = [UIStoryboard viewControllerWithIdentifier:@"MNDWhatIsPlusTenderViewController"];
    alertVC.titleStr = sender.titleLabel.text;
    if (self.problemArray.count <= 0) {//防止崩溃
        return;
    }
    MNDCommonProblemModel *problemModel = self.problemArray[0];
    alertVC.tipStr = problemModel.answer;
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self addChildViewController:alertVC];
    //    __weak typeof(self) weakSelf = self;
    [alertVC.iKonwBtn bk_addEventHandler:^(id sender) {
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainView.frame = CGRectMake(alertVC.alertContainView.frame.origin.x, kScreenHeight, alertVC.alertContainView.frame.size.width, alertVC.alertContainView.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
            
        }];
    } forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MNDAutoTenderPlusCell *cell = [tableView dequeueReusableCellWithIdentifier:kMNDAutoTenderPlusCell];
    MNDPlusTenderModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([MNDLoginUserModel isUserLogin]) {
        MNDPlusDetailRootViewController *detailVC = [UIStoryboard viewControllerWithIdentifier:@"MNDPlusDetailRootViewController"];
        MNDPlusTenderModel *model = self.dataArray[indexPath.row];
        detailVC.tenderModel = model;
        [self.navigationController pushViewController:detailVC animated:YES];
    }else {
        [self goToLoginVC];
    }
    
}

#pragma mark -没有登录，跳转到登录页面

- (void)goToLoginVC {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    UINavigationController *naviVC = [storyboard instantiateInitialViewController];
    
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];
}

#pragma mark - 无数据显示图片
- (void)creatMaskView {
    UIView *maskView = [[UIView alloc]initWithFrame:self.view.bounds];
    maskView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
    //    [self.view insertSubview:maskView aboveSubview:self.tableView];
    [self.tableView addSubview:maskView];
    UIImageView *imgV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"blankpage_emptydata"]];
    UILabel *tipLabel = [[UILabel alloc]init];
    tipLabel.text = @"哎呀~这里空空如也~";
    tipLabel.font = [UIFont systemFontOfSize:14];
    tipLabel.textColor = kColorGray;
    
    [maskView addSubview:tipLabel];
    [maskView addSubview:imgV];
    
    imgV.layer.cornerRadius = imgV.bounds.size.height*0.5;
    imgV.clipsToBounds = YES;
    [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(maskView);
        make.centerY.equalTo(maskView).mas_offset(-80);
    }];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(imgV);
        make.top.equalTo(imgV.mas_bottom).offset(10);
    }];
    
    self.placeHolderMaskView = maskView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
